import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import store from '@/store'
import Cookies from 'js-cookie'
import { clearLoginInfo } from '@/api/user/index'

// 动态加载
const modules = import.meta.glob('../views/**/**.vue')
const _import = (key: string) => {
  return modules[`../views/${key}.vue`]
}

// 全局路由(无需嵌套上左右整体布局)
const globalRoutes: Array<RouteRecordRaw> = [
  { path: '/404', component: () => import('@/views/common/404.vue'), name: '404', meta: { title: '404未找到' } },
  { path: '/login', component: () => import('@/views/common/login.vue'), name: 'login', meta: { title: '登录' } },
  {
    path: '/redirect',
    component: () => import('@/views/layout/main.vue'),
    redirect: { name: 'redirect' },
    children: [
      {
        path: '/redirect/:path(.*)',
        component: () => import('@/views/common/redirect.vue')
      }
    ]
  },
]

const mainRoutes: RouteRecordRaw = {
  path: '/',
  name: 'main',
  component: () => import('@/views/layout/main.vue'),
  redirect: { name: 'home' },
  meta: { title: '主入口整体布局' },
  children: [
    // 通过meta对象设置路由展示方式
    // 1. isTab: 是否通过tab展示内容, true: 是, false: 否
    // 2. iframeUrl: 是否通过iframe嵌套展示内容, '以http[s]://开头': 是, '': 否
    // 提示: 如需要通过iframe嵌套展示内容, 但不通过tab打开, 请自行创建组件使用iframe处理!
    { path: '/home', component: () => import('@/views/common/home.vue'), name: 'home', meta: { title: '首页' } }
  ],
  beforeEnter (to, from, next) {
    let token = Cookies.get('token')
    if (!token || !/\S/.test(token)) {
      clearLoginInfo()
      next({ name: 'login' })
    }
    next()
  }
}

const router = createRouter({
  history: createWebHashHistory(),
  scrollBehavior () {
    return { top: 0 }
  },
  routes: globalRoutes.concat(mainRoutes)
})

router.beforeEach((to, from, next) => {
  routeHandle(to)
  if (to.meta.title) {
    document.title = <string>to.meta.title
  }
  if (store.state.common.isAddDynamicMenuRoutes || fnCurrentRouteType(to, globalRoutes) === 'global') {
    next()
  } else {
    let menuList = [{"menuId":1,"parentId":0,"parentName":null,"name":"系统管理","url":null,"perms":null,"type":0,"icon":"system","orderNum":0,"open":null,"list":[{"menuId":2,"parentId":1,"parentName":null,"name":"管理员列表","url":"sys/user","perms":null,"type":1,"icon":"admin","orderNum":1,"open":null,"list":null},{"menuId":3,"parentId":1,"parentName":null,"name":"角色管理","url":"sys/role","perms":null,"type":1,"icon":"role","orderNum":2,"open":null,"list":null},{"menuId":4,"parentId":1,"parentName":null,"name":"菜单管理","url":"sys/menu","perms":null,"type":1,"icon":"menu","orderNum":3,"open":null,"list":null},{"menuId":5,"parentId":1,"parentName":null,"name":"SQL监控","url":"http://gbkjk.com/prodApi/druid/sql.html","perms":null,"type":1,"icon":"sql","orderNum":4,"open":null,"list":null},{"menuId":6,"parentId":1,"parentName":null,"name":"定时任务","url":"job/schedule","perms":null,"type":1,"icon":"job","orderNum":5,"open":null,"list":null},{"menuId":27,"parentId":1,"parentName":null,"name":"参数管理","url":"sys/config","perms":"sys:config:list,sys:config:info,sys:config:save,sys:config:update,sys:config:delete","type":1,"icon":"config","orderNum":6,"open":null,"list":null},{"menuId":30,"parentId":1,"parentName":null,"name":"文件上传","url":"oss/oss","perms":"sys:oss:all","type":1,"icon":"oss","orderNum":6,"open":null,"list":null},{"menuId":29,"parentId":1,"parentName":null,"name":"系统日志","url":"sys/log","perms":"sys:log:list","type":1,"icon":"log","orderNum":7,"open":null,"list":null}]},{"menuId":30,"parentId":0,"parentName":null,"name":"组件列表","url":null,"perms":null,"type":0,"icon":"system","orderNum":0,"open":null,"list":[{"menuId":31,"parentId":30,"parentName":null,"name":"wangeditor","url":"zujian/wangeditor","perms":null,"type":1,"icon":"admin","orderNum":1,"open":null,"list":null},{"menuId":32,"parentId":30,"parentName":null,"name":"quill","url":"zujian/quill","perms":null,"type":1,"icon":"admin","orderNum":1,"open":null,"list":null}]}]
    fnAddDynamicMenuRoutes(menuList)
    store.commit('common/updateAddMenuRouters', true)
    sessionStorage.setItem('menuList', JSON.stringify(menuList || '[]'))
    next({ ...to, replace: true })
  }
})

/**
 * 判断当前路由类型, global: 全局路由, main: 主入口路由
 * @param {*} route 当前路由
 */
 function fnCurrentRouteType (route: any, globalRoutes: Array<any> = []) : any {
  var temp: Array<any> = []
  for (var i = 0; i < globalRoutes.length; i++) {
    if (route.path === globalRoutes[i].path) {
      return 'global'
    } else if (globalRoutes[i].children && globalRoutes[i].children.length >= 1) {
      temp = temp.concat(globalRoutes[i].children)
    }
  }
  return temp.length >= 1 ? fnCurrentRouteType(route, temp) : 'main'
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
 function fnAddDynamicMenuRoutes (menuList: Array<any> = [], routes: Array<any> = []) {
  let temp: Array<any> = []
  for (var i = 0; i < menuList.length; i++) {
    if (menuList[i].list && menuList[i].list.length >= 1) {
      temp = temp.concat(menuList[i].list)
    } else if (menuList[i].url && /\S/.test(menuList[i].url)) {
      menuList[i].url = menuList[i].url.replace(/^\//, '')
      var route = {
        path: menuList[i].url.replace('/', '-'),
        component: null,
        name: menuList[i].url.replace('/', '-'),
        meta: {
          menuId: menuList[i].menuId,
          title: menuList[i].name,
          isDynamic: true,
          isTab: true,
          iframeUrl: ''
        }
      }
      // url以http[s]://开头, 通过iframe展示
      if (/^http[s]?:\/\/.*/.test(menuList[i].url)) {
        route['path'] = `i-${menuList[i].menuId}`
        route['name'] = `i-${menuList[i].menuId}`
        route['meta']['iframeUrl'] = menuList[i].url
      } else {
        try {
          route['component'] = _import(`modules/${menuList[i].url}`)
        } catch (e) {}
      }
      routes.push(route)
    }
  }
  if (temp.length >= 1) {
    fnAddDynamicMenuRoutes(temp, routes)
  } else {
    mainRoutes.name = 'main-dynamic'
    mainRoutes.children = routes
    router.addRoute(mainRoutes)
    router.addRoute({ path: '/:pathMatch(.*)*', redirect: { name: '404' } })
    sessionStorage.setItem('dynamicMenuRoutes', JSON.stringify(mainRoutes.children || '[]'))
    console.log('\n')
    console.log('%c!<-------------------- 动态(菜单)路由 s -------------------->', 'color:blue')
    console.log(mainRoutes.children)
    console.log('%c!<-------------------- 动态(菜单)路由 e -------------------->', 'color:blue')
  }
}

// 路由操作
function routeHandle(route: any) {
  let mainTabs = store.getters['common/getMainTabs']
  if (route.meta.isTab) {
    // tab选中, 不存在先添加
    var tab = mainTabs.filter((item: any) => item.name === route.name)[0]
    if (!tab) {
      if (route.meta.isDynamic) {
        let dynamicMenuRoutes = JSON.parse(sessionStorage.getItem('dynamicMenuRoutes') || '[]')
        route = dynamicMenuRoutes.filter((item: any) => item.name === route.name)[0]
        if (!route) {
          return console.error('未能找到可用标签页!')
        }
      }
      tab = {
        menuId: route.meta.menuId || route.name,
        name: route.name,
        title: route.meta.title,
        type: /^http[s]?:\/\/.*/.test(route.meta.iframeUrl) ? 'iframe' : 'module',
        iframeUrl: route.meta.iframeUrl || ''
      }
      store.commit('common/updateMainTabs', mainTabs.concat(tab))
    }
    store.commit('common/updateMenuActiveName', tab.menuId + '')
    store.commit('common/updateMainTabsActiveName', tab.name)
  }
}

export default router
